<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click=" dialogVisible=true">上传图片
    </el-button>
    <el-dialog :visible.sync="dialogVisible">
      <el-upload
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        :http-request="uploadFile"
        :action="actionUrl"
        class="editor-slide-upload"
        list-type="picture-card">
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-button size="small" @click="handleVisibleFun">取 消</el-button>
      <el-button size="small" type="primary" @click="handleSubmit">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from 'api/qiniu'
import axios from 'axios'
export default {
  name: 'EditorSlideUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    }
  },
  data() {
    return {
      actionUrl: '',
      dialogVisible: false,
      fileList: []
    }
  },
  created() {
    this.initUploadFileurl()
  },
  methods: {
    initUploadFileurl() {
      this.actionUrl = process.env.BASE_API + 'file/uploadImageAndCrtThumbImagesRichEdit'
    },
    uploadFile(content) {
      const fd = new FormData()
      fd.append('images', content.file)
      fd.append('resPath', this.resPath)

      const fileSize = fd.size / 1024 / 1024
      if (fileSize > 2) {
        this.$message({
          message: '上传图片不能大于2M',
          type: 'warning'
        })
      } else {
        const loading = this.$loading({
          lock: true,
          text: '保存中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        axios.post(content.action, fd).then(res => {
          loading.close()
          if (res.data.code === 1) {
            var listObj = {}
            listObj.url = res.data.data[0].maxImageUrl
            this.fileList.push(listObj)
            this.$message({
              message: '上传成功',
              type: 'success'
            })
            console.log(res.data.data)
          } else {
            this.$message({
              message: res.data.msg,
              type: 'warning'
            })
          }
        })
      }
    },
    handleSubmit() {
      this.$emit('successCBK', this.fileList)
      this.dialogVisible = false
      this.fileList = []
    },
    handleRemove(file) {
      var _this = this
      this.fileList.forEach(function(item, index) {
        if (file.uid === item.uid) {
          _this.fileList.splice(index, 1)
        }
      })
    },
    handleVisibleFun() {
      this.dialogVisible = false
      this.fileList = []
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
.editor-slide-upload {
  margin-bottom: 20px;
  /deep/ .el-upload--picture-card {
    width: 100%;
  }
}
</style>
